package com.wandian.games.mvvm.gamehome;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.component.dly.xzzq_ywsdk.YwSDK;
import com.component.dly.xzzq_ywsdk.YwSDK_WebActivity;
import com.duoyou.task.openapi.DyAdApi;
import com.iBookStar.views.YmConfig;
import com.ledong.lib.leto.Leto;
import com.mgc.leto.game.base.MgcAccountManager;
import com.mgc.leto.game.base.bean.LoginResultBean;
import com.mgc.leto.game.base.listener.SyncUserInfoListener;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.bean.UserInfoBean;
import com.mylib.libcore.config.CoinTypeEnum;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.eventbus.ChangeMessage;
import com.mylib.libcore.mvvm.BaseMVVMFragment;
import com.mylib.libcore.utils.DevicesIDUtil;
import com.mylib.libcore.utils.JsonUtil;
import com.mylib.libcore.utils.UIUtils;
import com.wandian.games.R;
import com.wandian.games.adapter.TodayTaskRecycleAdapter;
import com.wandian.games.databinding.GamesFragmentHomeBinding;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Random;

import me.jessyan.autosize.utils.ScreenUtils;

import static com.mylib.libcore.config.AppConfig.DUOYOU_APP_ID;
import static com.mylib.libcore.config.AppConfig.DUOYOU_AppSecret;
import static com.mylib.libcore.config.AppSPKeyConfig.APP_CHANNEL;
import static com.mylib.libcore.config.AppSPKeyConfig.APP_OA_ID;

/**
 * @author Administrator
 * @date 2019/12/16-13:30
 * @description 试玩fragment
 **/
@Route(path = RouterConfig.ROUTER_FRAGMENT_GAMES_HOME)
public class GamesHomeFragment extends BaseMVVMFragment<GamesHomeFragmentViewModel>  {

    private GamesFragmentHomeBinding dataBinding;
    private TodayTaskRecycleAdapter todayTaskRecycleAdapter;
    private UserInfoBean userInfoBean;
    private int pageNum =1;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        dataBinding = DataBindingUtil.inflate(inflater, R.layout.games_fragment_home, container, false);
        return dataBinding.getRoot();
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        dataBinding.setViewModel(mViewModel);
        if(!UIUtils.isEmpty(dataBinding)) EventBus.getDefault().register(this);
        LinearLayout.LayoutParams linearParams =(LinearLayout.LayoutParams) dataBinding.viewSys.getLayoutParams(); //取控件textView当前的布局参数 linearParams.height = 20;// 控件的高强制设成20
        linearParams.height = ScreenUtils.getStatusBarHeight();;
        dataBinding.viewSys.setLayoutParams(linearParams);
        userInfoBean = AppContext.getInstance().getAppPreferencesHelper().getUserInfoBean();
        initClink();
        initViewData();
        initRecycleView();
       // mViewModel.getXWList(getContext());
     //   mViewModel.getYWHZList(getContext());
        mViewModel.getGameDuoYouData(getContext(),pageNum);
    }


    private void initRecycleView(){
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        dataBinding.recycler.setLayoutManager(layoutManager);
        todayTaskRecycleAdapter  = new TodayTaskRecycleAdapter(R.layout.games_item_today_task_style_one);
        dataBinding.recycler.setAdapter(todayTaskRecycleAdapter);

        dataBinding.recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                try {
                    if(recyclerView.canScrollVertically(1)){
                    }else {
                        if(todayTaskRecycleAdapter.getData().size()>=20 &&  mViewModel.haveMore){
                            pageNum = pageNum+1;
                            Log.d("changeGames",pageNum+"changeGames----wwwww-"+ mViewModel.haveMore );
                            mViewModel.getGameDuoYouData(getContext(),pageNum);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private void initClink(){
        dataBinding.llGame1.setOnClickListener(v -> {
            UIUtils.setKeyEveryDayCoin(CoinTypeEnum.GAME_COIN);
            if(UIUtils.isFastClick()){
                return;
            }
            if(!UIUtils.isEmpty(userInfoBean)){
                //小游戏启动游戏中心
                MgcAccountManager.syncAccount(getContext(),
                        userInfoBean.getId()+"", "",
                        userInfoBean.getNickName()+"",
                        userInfoBean.getHeadPic()+"", true,  new SyncUserInfoListener() {
                            @Override
                            public void onSuccess(LoginResultBean data) {
                                Log.d("MgcAccountManager","onSuccess");
                            }

                            @Override
                            public void onFail(String code, String message) {
                                Log.d("MgcAccountManager","onFail");
                            }
                        });
                Leto.getInstance().startGameCenter (getContext());
            }

//            //闲玩
//            XWADPage.jumpToAD(new XWADPageConfig.Builder(AppContext.getInstance().getAppPreferencesHelper().getKeyValue("user_id")) //必传参数，指接入方渠道的APP的用户ID，要求每个用户唯一，且不变
//                    .pageType(XWADPageConfig.PAGE_AD_LIST)
//                    .msaOAID(AppContext.getInstance().getAppPreferenceForever().getAppOAID())//指的是接入了安全联盟sdk后，获取的用户的oaid，获取不到可不用设置 或者传 空/null 不可乱传
//                    .build());

        });
        dataBinding.llGame2.setOnClickListener(v -> {
            UIUtils.setKeyEveryDayCoin(CoinTypeEnum.GAME_COIN);
            //多游
            String oa_id =   AppContext.getInstance().getAppPreferenceForever().getAppOAID();
            if(!UIUtils.isEmpty(oa_id))DyAdApi.getDyAdApi().setOAID(oa_id);
            DyAdApi.getDyAdApi().setTitleBarColor(R.color.sys_text_color);
            DyAdApi.getDyAdApi().setTitle("多游游戏");
            DyAdApi.getDyAdApi().jumpAdList(getContext(), AppContext.getInstance().getAppPreferencesHelper().getKeyValue("user_id"), 0);
        });
        dataBinding.llGame3.setOnClickListener(v -> {
            UIUtils.setKeyEveryDayCoin(CoinTypeEnum.GAME_COIN);
            //鱼玩
            String oa_id = AppContext.getInstance().getAppPreferenceForever().getAppOAID();
            YwSDK.Companion.refreshMediaUserId(AppContext.getInstance().getAppPreferencesHelper().getKeyValue("user_id"));
            if(UIUtils.isEmpty(oa_id)){
                YwSDK.Companion.refreshOaid(DevicesIDUtil.getDeviceIDAll(getContext()));
            }else {
                YwSDK.Companion.refreshOaid(oa_id+ "");
            }
            //进入鱼玩盒子首页
            YwSDK_WebActivity.Companion.open(getContext());

        });
        dataBinding.llGame4.setOnClickListener(v -> {
            UIUtils.setKeyEveryDayCoin(CoinTypeEnum.NOVEL_COIN);
            //配置落地页TitleBar的背景颜色和文字颜色
            YmConfig.setTitleBarColors(0xffffffff, 0xff000000);
//            YmConfig.setTitleBarColors(R.color.color_sys, R.color.white);
            YmConfig.setOutUserId(AppContext.getInstance().getAppPreferencesHelper().getKeyValue("user_id"));			//对接金币必须事先调用此接口
            YmConfig.openReader();
        });

    }



    private void initViewData(){
        mViewModel.listTodayBean.observe(this,listTodayBean -> {
            if(!UIUtils.isEmpty(listTodayBean)){
                if(pageNum==1){
                    todayTaskRecycleAdapter.setNewData(listTodayBean);
                }else {
                    todayTaskRecycleAdapter.addData(listTodayBean);
                    todayTaskRecycleAdapter.loadMoreComplete();
                }
                if(listTodayBean.size()<20){
                    mViewModel.haveMore = false;
                }else {
                    mViewModel.haveMore = true;
                }
            }
        });
    }



   @Subscribe(threadMode = ThreadMode.MAIN)
   public void eventBusMessage(ChangeMessage changeMessage) {
       try {
           if(!UIUtils.isEmpty(changeMessage) && !UIUtils.isEmpty(changeMessage.getIsChange())){
               //changeGames
               if(changeMessage.getIsChange().equals("changeGames")){
                   Log.d("changeGames","changeGames" );
               }
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
   }

    @Override
    public void onDestroy() {
        try {
            EventBus.getDefault().unregister(this);
        }catch (Exception e){}
        super.onDestroy();
    }

}
